<template>
  <div class="dashboard-container">
    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon singer-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.singerCount }}</div>
              <div class="stat-label">歌手数量</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon song-icon">
              <el-icon><Mic /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.songCount }}</div>
              <div class="stat-label">歌曲数量</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon rank-icon">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.rankCount }}</div>
              <div class="stat-label">榜单数量</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon user-icon">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ stats.consumerCount }}</div>
              <div class="stat-label">用户数量</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-container">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>歌手性别分布</span>
            </div>
          </template>
          <div ref="genderChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>歌曲上传趋势</span>
            </div>
          </template>
          <div ref="trendChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { User, Mic, Trophy, UserFilled } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import api from '@/services/api'

export default {
  name: 'Dashboard',
  components: {
    Mic,
    User,
    Trophy,
    UserFilled
  },
  setup() {
    // 统计数据
    const stats = reactive({
      singerCount: 0,
      songCount: 0,
      rankCount: 0,
      consumerCount: 0
    })

    // 图表实例
    const genderChart = ref(null)
    const trendChart = ref(null)
    let genderChartInstance = null
    let trendChartInstance = null

    const genderStats = reactive({
      male: 0,
      female: 0
    })

    /**
     * 获取统计数据
     */
    const fetchStats = async () => {

      try {

        const singerResponse = await api.singer.numberOfSinger()
        if (singerResponse.code ==='1'){
          stats.singerCount = singerResponse.data
        }else {
          console.warn('获取歌手数量失败:', singerResponse.msg)
          stats.singerCount = 0
        }

        const songResponse = await api.song.numberOfSong()
        if (songResponse.code === '1'){
          stats.songCount = songResponse.data
        }else {
          console.warn('获取歌曲数量失败:', songResponse.msg)
          stats.songCount = 0
        }

        const rankResponse = await api.rank.numberOfRank()
        if (rankResponse.code === '1'){
          stats.rankCount = rankResponse.data
        }else{
          console.warn('获取榜单数量失败:', rankResponse.msg)
          stats.rankCount = 0
        }

        // 获取用户数量
        const consumerResponse = await api.consumer.numberOfConsumer()
        if(consumerResponse.code === '1'){
          stats.consumerCount = consumerResponse.data
        }else {
          console.warn('获取用户数量失败:', consumerResponse.msg)
          stats.consumerCount = 0
        }

        await fetchGenderStats()
      } catch ( error){
        console.error('获取统计数据失败:', error)
        stats.singerCount = 0
        stats.rankCount = 0
        stats.songCount = 0
        stats.consumerCount = 0
        genderStats.male = 0
        genderStats.female = 0
      }
    }

    /**
     * 获取性别统计数据
     */
    const fetchGenderStats = async () => {
      try {
        // 获取男歌手数量 (假设1代表男性)
        const maleResponse = await api.singer.numberOfSingerBySex(1)
        if (maleResponse.code === '1') {
          genderStats.male = maleResponse.data || 0
        } else {
          console.warn('获取男歌手数量失败:', maleResponse.msg)
          genderStats.male = 0
        }

        // 获取女歌手数量 (假设0代表女性)
        const femaleResponse = await api.singer.numberOfSingerBySex(0)
        if (femaleResponse.code === '1') {
          genderStats.female = femaleResponse.data || 0
        } else {
          console.warn('获取女歌手数量失败:', femaleResponse.msg)
          genderStats.female = 0
        }

        // 更新性别分布图表
        updateGenderChart()
      } catch (error) {
        console.error('获取性别统计数据失败:', error)
        genderStats.male = 0
        genderStats.female = 0
      }
    }

    /**
     * 初始化性别分布图表
     */
    const initGenderChart = () => {
      if (genderChart.value) {
        genderChartInstance = echarts.init(genderChart.value)
        const option = {
          title: {
            text: '歌手性别分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '性别',
              type: 'pie',
              radius: '50%',
              data: [
                { value: genderStats.male, name: '男歌手' },
                { value: genderStats.female, name: '女歌手' }
              ],
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        genderChartInstance.setOption(option)
      }
    }

    /**
     * 更新性别分布图表
     */
    const updateGenderChart = () => {
      if (genderChartInstance) {
        const option = {
          series: [
            {
              data: [
                { value: genderStats.male, name: '男歌手' },
                { value: genderStats.female, name: '女歌手' }
              ]
            }
          ]
        }
        genderChartInstance.setOption(option)
      }
    }

    /**
     * 初始化趋势图表
     */
    const initTrendChart = () => {
      if (trendChart.value) {
        trendChartInstance = echarts.init(trendChart.value)
        const option = {
          title: {
            text: '歌曲上传趋势',
            left: 'center'
          },
          xAxis: {
            type: 'category',
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: [0, 0, 0, 0, 0, 0, 0],
              type: 'line',
              smooth: true
            }
          ]
        }
        trendChartInstance.setOption(option)
      }
    }

    /**
     * 窗口大小改变时重置图表大小
     */
    const resizeCharts = () => {
      if (genderChartInstance) {
        genderChartInstance.resize()
      }
      if (trendChartInstance) {
        trendChartInstance.resize()
      }
    }

    // 组件挂载时初始化
    onMounted(() => {
      fetchStats()
      initGenderChart()
      initTrendChart()

      // 监听窗口大小变化
      window.addEventListener('resize', resizeCharts)
    })

    // 组件卸载前清理
    onBeforeUnmount(() => {
      // 销毁图表实例
      if (genderChartInstance) {
        genderChartInstance.dispose()
      }
      if (trendChartInstance) {
        trendChartInstance.dispose()
      }

      // 移除事件监听
      window.removeEventListener('resize', resizeCharts)
    })

    return {
      stats,
      genderChart,
      trendChart
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
}

.singer-icon {
  background-color: #e6f7ff;
  color: #1890ff;
}

.song-icon {
  background-color: #fff7e6;
  color: #fa8c16;
}

.rank-icon {
  background-color: #f9f0ff;
  color: #722ed1;
}

.user-icon {
  background-color: #f6ffed;
  color: #52c41a;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.charts-container {
  margin-top: 20px;
}

.chart-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: bold;
  color: #333;
}

.chart-container {
  width: 100%;
  height: 300px;
}
</style>
